package com.qianda.qdminiapp.service.protocols;

import com.alibaba.fastjson.JSON;
import com.qianda.qdminiapp.common.constant.CommonConstant;
import com.qianda.qdminiapp.common.exception.SimpleException;
import com.qianda.qdminiapp.common.util.HttpsUtil;
import com.qianda.qdminiapp.controller.Result;
import com.qianda.qdminiapp.dao.device.DeviceDao;
import com.qianda.qdminiapp.dao.order.OrderDao;
import com.qianda.qdminiapp.dao.order.QqdOrderLogsDao;
import com.qianda.qdminiapp.domain.model.device.Device;
import com.qianda.qdminiapp.domain.model.order.Order;
import com.qianda.qdminiapp.domain.model.order.QqdOrderLogs;
import com.qianda.qdminiapp.common.exception.ExceptionCode;
import com.qianda.qdminiapp.service.CommondManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName DeviceProtocolsV1
 * @Author cw
 * @Date 2019/8/7 9:20
 * @Version 1.0
 */
@Service
@Transactional
public class DeviceProtocolsV1 implements CommondManager {

    private static Logger LOGGER = LoggerFactory.getLogger(DeviceProtocolsV1.class);

    private OrderDao orderDao;
    private QqdOrderLogsDao qqdOrderLogsDao;
    private DeviceDao deviceDao;

    public DeviceProtocolsV1(OrderDao orderDao, QqdOrderLogsDao qqdOrderLogsDao, DeviceDao deviceDao) {
        this.orderDao = orderDao;
        this.qqdOrderLogsDao = qqdOrderLogsDao;
        this.deviceDao = deviceDao;
    }


    @Override
    @Transactional
    public Result startCreateTowel(String orderId) {

        //当前订单详情
        Order order = orderDao.selectById(orderId);

        if(order == null){
            throw new SimpleException(ExceptionCode.EX_HTTP_INPUT_NOT_ENTATY);
        }

        //判断订单是否已完成
        if(order.getOrderStatus() == CommonConstant.OrderStatus.ORDER_STATUS_FINISH){
            return Result.failure(ExceptionCode.EX_ORDER_FINISH.code(),ExceptionCode.EX_ORDER_FINISH.message());
        }
        QqdOrderLogs qqdOrderLogs = new QqdOrderLogs();
        qqdOrderLogs.setOrderLogCmd("0001");
        qqdOrderLogs.setOrderLogOrderId(orderId);
        qqdOrderLogs.setOrderLogCreateTime(LocalDateTime.now());
        qqdOrderLogs.setOrderLogReturnInfo("此订单已经出巾完成");
        qqdOrderLogsDao.insert(qqdOrderLogs);

        Integer outputCount =  order.getOrderTowelCount();
        if (outputCount == null || outputCount <= 1) {
            outputCount = 1;
        }
        LOGGER.info("设备出巾数量为：" + outputCount + "条");
        Device device = deviceDao.selectById(order.getOrderDeviceId());
        LOGGER.info("此设备imei值为：" + device.getDeviceCcid());


         if(device.getDeviceType() == 12){
            //发送设置
             Boolean isSuccess = deviceSetting(order, device);
            if(isSuccess){
                //发送成功，开始做巾
                deviceOutTowel(device.getDeviceCcid(),order,outputCount,device);
            }else{
                //发送失败，尝试再发一次
                Boolean isSuccessSec = deviceSetting(order, device);
                if(isSuccessSec){
                    //设置成功，开始做巾
                    deviceOutTowel(device.getDeviceCcid(),order,outputCount,device);
                }else{
                    //设置失败
                   throw new SimpleException(ExceptionCode.EX_ORDER_SETTING_ERROR);
                }
            }

         }
        LOGGER.info("出巾指令发送成功！");
        return Result.success();
    }

    /*
     * 设备设置
     * @Description
     * @Author cw
     * @Date 10:42 2019/8/7
     * @Param [settingMap, settingUrl, order, towelLength]
     * @return java.lang.Boolean
     **/
    private Boolean deviceSetting(Order order,Device device){
        String settingUrl = "http://wxapp.wst1688.com/admin/out/qqd_setLenth";// 设置长度
        String towelLength = order.getOrderDeviceLength().toString();
        if (Integer.parseInt(towelLength) / 100 == 0 && Integer.parseInt(towelLength) / 10 != 0) {
            towelLength = "0" + towelLength;
        } else if (Integer.parseInt(towelLength) / 10 == 0) {
            towelLength = "00" + towelLength;
        }
        LOGGER.info("出巾长度：" + towelLength);

        // 发送设置命令
        Map<String, Object> settingMap = new HashMap<String, Object>();
        settingMap.put("imei", device.getDeviceCcid()); // 设备imei
        settingMap.put("user_id", "2017");
        settingMap.put("key", "qqdwbdy");
        settingMap.put("tcpMsg", "0C00|00001| | |" + towelLength + ".");

        LOGGER.info("--发送毛巾机设备设置：" + "0C00|00001| | |" + towelLength + ".");
        qqdOrderLogsDao.insert(new QqdOrderLogs("0C00|00001| | |" + towelLength + ".",order.getOrderId()));

        //TODO
        //String resultStr = HttpsUtil.post(settingUrl, settingMap);
        String resultStr = "resultReturn:2";

//        qqdOrderLogsDao.insert(new QqdOrderLogs(resultStr, order.getOrderId(), "0002"));
//        Map<String, Object> resultMap  = (Map<String, Object>) JSON.parse(resultStr);
//        LOGGER.info("设置返回的值为：" + resultMap);
//        if(resultMap != null){
//            if ((Double) resultMap.get("resultReturn") == 1) {
//                LOGGER.info("设置成功，不需重新设置");
//                LOGGER.info("此设置订单号为：" + order.getOrderId());
//                // 设置成功，订单使用次数更新为1
//                order.setOrderSetCheck(1);
//                orderDao.updateById(order);
//                return true;
//            }
//        }

        //return false;
        //TODO
        LOGGER.info("订单设置成功");
        return true;//测试
    }

    /*
     * 出巾
     * @Description
     * @Author cw
     * @Date 11:07 2019/8/7
     * @Param [imei, order, outCount, device]
     * @return void
     **/
    private void deviceOutTowel(String imei,Order order,Integer outCount,Device device){
        String towelOutUrl = "http://wxapp.wst1688.com/admin/out/qqd_passthrough";// 出巾命令

        LOGGER.info("开始发送出巾命令，订单号为：" + order.getOrderId());
        // 发送出巾命令
        Map<String, Object> sendTowelOut = new HashMap<String, Object>();
        sendTowelOut.put("imei",imei ); // 设备imei
        sendTowelOut.put("user_id", "2017");
        sendTowelOut.put("key", "qqdwbdy");
        sendTowelOut.put("tcpMsg", "0D00|" + order.getOrderId() + "|0" + outCount + ".");
        LOGGER.info("--发送毛巾机设备出巾命令：" + "0D00|" + order.getOrderId() + "|0" + outCount + ".");
      //  this.insertOrderLogs("0D00|" + orderId + "|0" + outputCount + ".", null);
        qqdOrderLogsDao.insert(new QqdOrderLogs("0D00|" + order.getOrderId() + "|0" + outCount + "."));
        //String resultStr2 = HttpsUtil.post(towelOutUrl, sendTowelOut);
        String resultStr2="发送成功";//测试
        System.out.println(resultStr2);
        qqdOrderLogsDao.insert(new QqdOrderLogs(resultStr2, order.getOrderId(), "0002"));

        //TODO 此方法不应该放在这里
        //毛巾余量减一
        deviceDao.deviceTowelCountMinusOne(device.getDeviceId());
        // 订单+1
        order.setOrderDashiCheck(1);
        orderDao.updateById(order);
        LOGGER.info("--结束-客户端请求毛巾，出巾并且写入ORDER表-------------- end Msg0400----------");
    }


}
